package cn.itcast.config;

import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.SecutityUserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private SecutityUserService secutityUserService;

    @Resource
    private PasswordEncoder passwordEncoder;

    //根据用户名查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 1/通过userName 获取到userInfo信息
         * 2/通过User（UserDetails）返回details。
         */
        //通过userName获取用户信息
        User user = secutityUserService.getUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("not found");
        }
        //定义权限列表.
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        //authorities.add(new SimpleGrantedAuthority("ROLE_"+ user.getRoles()));
        Set<Role> roles = user.getRoles();

        ArrayList<Role> arrayRole = new ArrayList<>();
        for (Role role : roles) {
            arrayRole.add(role);
        }

        for (int i = 0; i < arrayRole.size(); i++) {
            String keyword = arrayRole.get(i).getKeyword();
            authorities.add(new SimpleGrantedAuthority(keyword));
        }


        org.springframework.security.core.userdetails.User userDetails =
                new org.springframework.security.core.userdetails.User(user.getUsername(),passwordEncoder.encode(user.getPassword()),authorities);
        return userDetails;
    }
}
